﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Text;
using Business;
using System.Data;
using System.Web.Security;
public partial class admin_TrendReport : @base {
    TrendReportService ts = new TrendReportService();
    protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {

            MachineNameLabel.Text = "Trend Report for " + MACHINENAME;
            DataTable dt = ts.getMachineMatrixByMachineID(MACHINEID);

            Session["MachineMatrix"] = dt;


            DataTable dta = new DataTable();
            dta = getMatrix();
            Session["TaskTable"] = dta;
            Session["ReportValue"] = dta;
            setFromDateList();
            setToDateList();
            DataTable matrix = new DataTable();
            matrix.Columns.Add("x", typeof(string));
            Session["DeleteTable"] = matrix;

        }


    }
    //protected DataTable setMachineMatrix() {
    //    // Create a new table.
    //    DataTable taskTable = new DataTable("TaskList");

    //    // Create the columns.
    //    taskTable.Columns.Add("x", typeof(string));
    //    taskTable.Columns.Add("y", typeof(string));
    //    string component_id = DropDownClientList.SelectedValue.ToString();
    //    taskTable = ds.getDataByComponentID(component_id);
    //    //Persist the table in the Session object.
    //    if (taskTable.Rows.Count == 0) {
    //        string type = ds.getComponentType(component_id);
    //        DataTable temple = new DataTable();
    //        temple = ds.getDataByTypeID(type);
    //        foreach (DataRow r in temple.Rows) {
    //            DataRow tableRow = taskTable.NewRow();
    //            tableRow["Attribute"] = r["attribute"].ToString();
    //            tableRow["Value"] = "";
    //            taskTable.Rows.Add(tableRow);
    //        }

    //    }
    //    return taskTable;
    //}
    protected void setFromDateList() {
        //DataTable dt = (DataTable)Session["MachineMatrix"];
        //foreach (DataRow r in dt.Rows)
        //{
        //    String dateRecorded1 = r["date_recorded"].ToString();
        //    string dateRecorded = dateRecorded1.Trim();
        //    string dta = dateRecorded.Substring(0, dateRecorded.IndexOf(" ")).Trim();

        //    System.Web.UI.WebControls.ListItem ls = new System.Web.UI.WebControls.ListItem(dta, dateRecorded1, true);
        //    fromDate_DropDownList.Items.Add(ls);
        //}
        DataTable dt = ts.getMachineMatrixByMachineID(MACHINEID); //(DataTable)Session["MachineMatrix"];
        foreach (DataRow r in dt.Rows) {
            String dateRecorded1 = r["date"].ToString();
            string dateRecorded = dateRecorded1.Trim();
            string dta = dateRecorded;//.Substring(0, dateRecorded.IndexOf(" ")).Trim();

            System.Web.UI.WebControls.ListItem ls = new System.Web.UI.WebControls.ListItem(dta, dateRecorded1, true);
            fromDate_DropDownList.Items.Add(ls);
        }


    }
    protected void setToDateList() {
        //string fromDate = fromDate_DropDownList.SelectedValue.ToString();
        //System.DateTime str_date = DateTime.Parse(fromDate, System.Globalization.CultureInfo.CreateSpecificCulture("en-AU").DateTimeFormat);
        //DataRow[] dt = ((DataTable)Session["MachineMatrix"]).Select("date_recorded > #" + str_date.ToString() + "#");
        //foreach (DataRow r in dt)
        //{
        //    String dateRecorded1 = r["date_recorded"].ToString();
        //    string dateRecorded = dateRecorded1.Trim();
        //    string dta = dateRecorded.Substring(0, dateRecorded.IndexOf(" ")).Trim();      
        //    System.Web.UI.WebControls.ListItem ls = new System.Web.UI.WebControls.ListItem(dta, dateRecorded, true);
        //    toDate_DropBoxList.Items.Add(ls);
        //}
        DataTable dtb = ((DataTable)Session["MachineMatrix"]);
        if (dtb.Rows.Count != 0) {
            int index = fromDate_DropDownList.SelectedIndex;
            int i = 0;
            foreach (DataRow r in dtb.Rows) {
                String dateRecorded1 = r["date"].ToString();
                string dateRecorded = dateRecorded1.Trim();
                string dta = dateRecorded;
                System.Web.UI.WebControls.ListItem ls = new System.Web.UI.WebControls.ListItem(dta, dateRecorded1, true);
                toDate_DropBoxList.Items.Add(ls);
                i++;
                if (i >= index)
                    break;
            }

        }

    }

    protected void fromDate_changed(object sender, EventArgs e) {
        toDate_DropBoxList.Items.Clear();
        setToDateList();
    }
    protected DataTable getMatrix() {


        DataTable matrix = new DataTable();
        int fromDateIndex = fromDate_DropDownList.SelectedIndex;
        int toDateIndex = toDate_DropBoxList.SelectedIndex;

        matrix.Columns.Add("x", typeof(string));
        matrix.Columns.Add("y", typeof(string));
        DataTable dtb = ((DataTable)Session["MachineMatrix"]);
        int dtnum = dtb.Rows.Count;
        // string test = "num: "+dtnum+"/"+"fdate:"+fromDateIndex+"/todate:"+toDateIndex+"/";
        if (dtnum != 0 && toDateIndex >= 0) {
            for (int i = fromDateIndex; i >= toDateIndex; i--) {
                DataRow r = dtb.Rows[i];
                string daterecorded = r["date"].ToString();
                string matrixNo = r["matrix_no"].ToString();
                DataRow m = matrix.NewRow();
                m["x"] = daterecorded;
                m["y"] = matrixNo;
                matrix.Rows.Add(m);
            }
        }
        return matrix;
    }
    protected void setImageMapHotspot() {
        int intWidth = 480;
        int intHeight = 400;
        DataTable dt = (DataTable)Session["ReportValue"];
        int i = 0;
        int total = dt.Rows.Count + 1;
        foreach (DataRow r in dt.Rows) {
            string month = (r["x"].ToString());
            int matrix = ToInt(r["y"].ToString());
            i++;
            //  c.AddValue(i, matrix, month);
            CircleHotSpot Circle1 = new CircleHotSpot();
            Circle1.HotSpotMode = HotSpotMode.PostBack;
            Circle1.PostBackValue = month;
            Circle1.X = 30 + (intWidth - 2 * 30) * i / total;
            //145, 480 
            Circle1.Y = intHeight - 30 - (intHeight - 2 * 30) * matrix / 200;//120;
            Circle1.Radius = 15;
            Circle1.AlternateText = month;
            ImageMap2.HotSpots.Add(Circle1);

        }
    }
    protected void GetReport(object sender, EventArgs e) {

        //DataTable dt = new DataTable();
        //dt = getMatrix();
        //Session["ReportValue"] = dt;

        ////  Image1.ImageUrl = "GetTrendReportImage.aspx";
        //// Image2.ImageUrl = "GetTrendReportImage.aspx";
        //ImageMap2.ImageUrl = "../client/GetTrendReportImage.aspx";
        //ImageMap2.HotSpots.Clear();

        //setImageMapHotspot();
        //photoHyperLink.Text = "Click here to enlarge picture";
        //photoHyperLink.Style["text-align"] = "center";
        //photoHyperLink.Attributes.Add("href", "../client/GetLargeTrendReportImage.aspx");

        DataTable matrix = new DataTable();
        matrix.Columns.Add("x", typeof(string));
        Session["DeleteTable"] = matrix;
        DataTable dt = new DataTable();
        dt = getMatrix();
        Session["TaskTable"] = dt;
        Session["ReportValue"] = dt;
        BindData();


    }
    protected void GetValue(object sender, ImageMapEventArgs e) {
        // Response.Write("Hi," + e.ToString());
        //  TextBox1.Text = "hi" + e.PostBackValue;
        string jscript = "<script language='javascript'>alert(' " + e.PostBackValue + "')</script>";
        // Page.RegisterClientScriptBlock("keyClientBlock",jscript);
        this.ClientScript.RegisterClientScriptBlock(this.GetType(), "keyClientBlock", jscript);
        string url = "MachineStatus.aspx?machine_id=" + MACHINEID + "&date=" + e.PostBackValue;
        Server.Transfer(url);

    }
    protected void LoginStatus1_LoggingOut(object sender, LoginCancelEventArgs e) {


        Session.Contents.Remove("UserDetails");
        Session.Abandon();
        Session.Contents.RemoveAll();
        FormsAuthentication.SignOut();
        Response.Redirect("../Default.aspx");
    }

    //
    private void BindData() {

        TaskGridView.DataSource = Session["TaskTable"];
        TaskGridView.DataBind();
    }
    protected void TaskGridView_RowDataBound(object sender, GridViewRowEventArgs e) {
        if (e.Row.RowType == DataControlRowType.DataRow) {
            int i = e.Row.DataItemIndex;
            e.Row.Cells[0].ForeColor = Color.Blue;
            TextBox tb1 = (TextBox)e.Row.FindControl("TextBox1");
            tb1.Text = ((DataTable)(Session["TaskTable"])).Rows[i]["x"].ToString();

            // tb1.Text = showData.Rows[i]["Attributes"].ToString();
            TextBox tb2 = (TextBox)e.Row.FindControl("TextBox2");
            tb2.Text = ((DataTable)(Session["TaskTable"])).Rows[i]["y"].ToString();

        }

    }
    protected void TaskGridView_RowDeleting(Object sender, GridViewDeleteEventArgs e) {
        //int TableNumber = TaskGridView.Rows.Count;

        DataTable dt = (DataTable)Session["TaskTable"];
        int k = dt.Rows.Count;
        GridViewRow row = TaskGridView.Rows[e.RowIndex];

        string att = ((TextBox)(row.Cells[1].FindControl("TextBox1"))).Text.ToString();
        DataTable matrix = (DataTable)Session["DeleteTable"];
        DataRow m = matrix.NewRow();
        m["x"] = att;
        matrix.Rows.Add(m);
        Session["DeleteTable"] = matrix;
        // dt.Rows[row.DataItemIndex].Delete();
        dt.Rows.RemoveAt(e.RowIndex);
        k = dt.Rows.Count;
        Session["TaskTable"] = dt;
        BindData();

    }
    protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e) {
        //Retrieve the table from the session object.
        DataTable dt = (DataTable)Session["TaskTable"];

        //Update the values.
        GridViewRow row = TaskGridView.Rows[e.RowIndex];
        dt.Rows[row.DataItemIndex]["x"] = ((TextBox)(row.FindControl("TextBox1"))).Text;
        dt.Rows[row.DataItemIndex]["y"] = ((TextBox)(row.FindControl("TextBox2"))).Text;//((TextBox)(row.Cells[2].Controls[0])).Text;        

        /*
        dt.Rows[e.RowIndex]["Attribute"] = e.NewValues["Attribute"].ToString();
        dt.Rows[e.RowIndex]["Value"] = e.NewValues["Value"].ToString();*/
        Session["TaskTable"] = dt;
        //Reset the edit index.
        TaskGridView.EditIndex = -1;

        //Bind data to the GridView control.
        BindData();
    }
    protected void TaskGridView_RowEditing(object sender, GridViewEditEventArgs e) {
        //Set the edit index.
        TaskGridView.EditIndex = e.NewEditIndex;
        //Bind data to the GridView control.
        BindData();
    }

    protected void TaskGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) {
        //Reset the edit index.
        TaskGridView.EditIndex = -1;
        //Bind data to the GridView control.
        BindData();
    }
    protected DataTable setSession() {
        int tableNumber = TaskGridView.Rows.Count;
        DataTable taskTable = new DataTable("TaskList");

        // Create the columns.
        taskTable.Columns.Add("x", typeof(string));
        taskTable.Columns.Add("y", typeof(string));

        for (int i = 0; i < tableNumber; i++) {
            GridViewRow row = TaskGridView.Rows[i];
            string att = ((TextBox)(row.Cells[1].FindControl("TextBox1"))).Text.ToString();
            string val = ((TextBox)(row.Cells[1].FindControl("TextBox2"))).Text.ToString();
            DataRow tableRow = taskTable.NewRow();
            tableRow["x"] = att;
            tableRow["y"] = val;
            taskTable.Rows.Add(tableRow);

        }
        return taskTable;

    }
    protected void Button1_Click1(object sender, EventArgs e) {
        //DataTable matrix = new DataTable();
        //matrix.Columns.Add("x", typeof(string));
        //Session["DeleteTable"] = matrix;
        //DataTable dt = new DataTable();
        //dt = getMatrix();
        //Session["TaskTable"] = dt;
        //Session["ReportValue"] = dt;
        //BindData();

        DataTable dt = new DataTable();
        dt = getMatrix();
        Session["ReportValue"] = dt;

        //  Image1.ImageUrl = "GetTrendReportImage.aspx";
        // Image2.ImageUrl = "GetTrendReportImage.aspx";
        ImageMap2.ImageUrl = "../client/GetTrendReportImage.aspx";
        ImageMap2.HotSpots.Clear();

        setImageMapHotspot();
        photoHyperLink.Text = "Click here to enlarge picture";
        photoHyperLink.Style["text-align"] = "center";
        photoHyperLink.Attributes.Add("href", "../client/GetLargeTrendReportImage.aspx");

    }
    protected void AddAttribute(object sender, EventArgs e) {
        string attribute = txtAttribute.Text.ToString();
        string value = txtValue.Text.ToString();

        if (attribute == "") {

            string jscript = "<script language='javascript'>alert('Should input name of attribute')</script>";
            // Page.RegisterClientScriptBlock("keyClientBlock",jscript);
            this.ClientScript.RegisterClientScriptBlock(this.GetType(), "keyClientBlock", jscript);
        } else {

            int ok = 1;
            DataTable dt = (DataTable)Session["TaskTable"];
            foreach (DataRow r in dt.Rows) {
                string att = r["x"].ToString();
                if (attribute == att) {
                    ok = 0;
                    break;
                }
            }
            if (ok == 0) {
                string jscript = "<script language='javascript'>alert('Cannot add an old date again!')</script>";
                // Page.RegisterClientScriptBlock("keyClientBlock",jscript);
                this.ClientScript.RegisterClientScriptBlock(this.GetType(), "keyClientBlock", jscript);

            } else {
                DataRow newAttribute = dt.NewRow();
                newAttribute["x"] = attribute;
                newAttribute["y"] = value;

                dt.Rows.Add(newAttribute);
                Session["TaskTable"] = dt;
                txtAttribute.Text = "";
                txtValue.Text = "";
            }

        }
        BindData();

    }
    protected void save_Click(object sender, EventArgs e) {
        DataTable newTable = new DataTable();
        newTable = (DataTable)Session["TaskTable"];
        DataTable deleteTable = new DataTable();
        deleteTable = (DataTable)Session["DeleteTable"];
        // DataTable oldTable = (DataTable)Session["ReportValue"];
        // int k = dt.Rows.Count;
        //string component_id = DropDownClientList.SelectedValue.ToString();
        //  ts.updateMatrixInDateperiod(oldTable, newTable, MACHINEID);
        if (deleteTable != null)
            ts.deleteMatrix(deleteTable, MACHINEID);
        ts.updateMatrix(newTable, MACHINEID);
        string jscript = "<script language='javascript'>alert('Edit successfully!')</script>";
        //Page.RegisterClientScriptBlock("key2ClientBlock", jscript);
        this.ClientScript.RegisterClientScriptBlock(this.GetType(), "key2ClientBlock", jscript);

        DataTable dt = ts.getMachineMatrixByMachineID(MACHINEID);

        Session["MachineMatrix"] = dt;
        toDate_DropBoxList.Items.Clear();
        fromDate_DropDownList.Items.Clear();
        setFromDateList();
        setToDateList();

    }
}
